import JsLogger from './JsLogger'
import picker from '@ohos.file.picker'
import JsDataStore from './JsDataStore'
import { BusinessError } from '@ohos.base'
import { fileIo as fs } from '@kit.CoreFileKit';
import fileUri from '@ohos.file.fileuri';

export class JsDialog {
  constructor() {
  }

  private getSelectMaxSelectNumber(fileMode: number): number {
    switch (fileMode) {
      case 3:
        return 500;
      case 1:
      default:
        break;
    }
    return 1;
  }

  private getSelectMode(type: number): picker.DocumentSelectMode {
    switch (type) {
      case 0:
      case 1:
      case 3:
        break;
      case 2:
        return picker.DocumentSelectMode.FOLDER;
      case 4:
        return picker.DocumentSelectMode.FOLDER;
      default:
        break;
    }
    return picker.DocumentSelectMode.FILE;
  }

  isVideo(filter: string): boolean {
    return filter.includes("mp4") || filter.includes("MPEG")
      || filter.includes("MPG") || filter.includes("DAT")
      || filter.includes("MOV") || filter.includes("FLV");
  }

  isAudio(filter: string): boolean {
    return filter.includes("mp3") || filter.includes("wma") || filter.includes("ogg") || filter.includes("flac")
      || filter.includes("wv");
  }

  isImage(filter: string): boolean {
    return filter.includes("png") || filter.includes("jpeg")
      || filter.includes("jpg") || filter.includes("bmp")
  }

  async openFileDialog(handler: number, filter: Array<string>, type: number, dir: string): Promise<boolean> {
    // let config = {
    //   action: 'ohos.want.action.OPEN_FILE',
    //   parameters: {
    //     startMode: 'choose',
    //     fileSuffixFilters:"*"
    //   }
    // }
    //
    // let context = JsDataStore.getContext();
    //
    // context.startAbilityForResult(config).then((result) => {
    //   // 获取到文档文件的uri
    //   let select_item_list = result.want.parameters.select_item_list;
    //   JsLogger.info("select file: %{public}s", select_item_list.toString());
    //   // 有的系统是file://xxx/xxx/xx/xx
    //   JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, [select_item_list.toString()]);
    // }).catch((error) => {
    //   JsLogger.error("open file dialog result %{public}s", JSON.stringify(error));
    //   JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, []);
    // });
    // return true;
    if (filter.length >= 100 || 0 == filter.length) {
      filter = ['.*'];
    }
    try {
      let documentPicker = new picker.DocumentViewPicker();
      let DocumentSelectOptions = new picker.DocumentSelectOptions();
      DocumentSelectOptions.fileSuffixFilters = filter;
      DocumentSelectOptions.selectMode = this.getSelectMode(type);
      DocumentSelectOptions.maxSelectNumber = this.getSelectMaxSelectNumber(type);
      DocumentSelectOptions.defaultFilePathUri = 'file://docs' + dir;
      documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array<string>) => {
        JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, DocumentSelectResult)
        JsLogger.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' +
        JSON.stringify(DocumentSelectResult));
      }).catch((err: BusinessError) => {
        JsLogger.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, []);
      JsLogger.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
    }
    return true;
  }

  async saveFileDialog(handler: number, fileName: string, dir: string, filter: Array<string>): Promise<boolean> {
    // let config = {
    //   action: 'ohos.want.action.CREATE_FILE',
    //   parameters: {
    //     startMode: 'save',
    //     key_pick_file_name: [fileName],
    //     saveFile: fileName,
    //   }
    // }
    //
    // try {
    //   let context = JsDataStore.getContext()
    //   let result = await context.startAbilityForResult(config);
    //   JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, [result.want?.parameters?.pick_path_return.toString()]);
    // } catch (error) {
    //   JsLogger.info("startAbilityForResult Promise.Reject is called, error.code = %{public}s", error.code)
    //   JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, []);
    // }
    // return true;

    try {
      let DocumentSaveOptions = new picker.DocumentSaveOptions();
      DocumentSaveOptions.newFileNames = [fileName];

      for(let i = 0; i < filter.length; i++) {
        if(filter[i] === '所有文件(*)')
        {
          filter[i] = '所有文件(*)|'
        }
      }

      DocumentSaveOptions.fileSuffixChoices = filter;
      DocumentSaveOptions.defaultFilePathUri = 'file://docs' + dir;
      let documentPicker = new picker.DocumentViewPicker();


      documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult: Array<string>) => {
        /*NOTE：该接口返回时，会先创建一个空文件，然后再往里写入，这导致上层应用误判出已存在同名文件。故先删除(Beta6)*/
        this.deleteTempFile(DocumentSaveResult);
        JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, DocumentSaveResult);
        JsLogger.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ',
          JSON.stringify(DocumentSaveResult));
      }).catch((err: BusinessError) => {
        JsLogger.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err));
      });

    } catch (error) {
      let err: BusinessError = error as BusinessError;
      JsDataStore.getQtNativeModule("QPA").selectedFilesResult(handler, []);
      JsLogger.error('DocumentViewPicker failed with err: ' + JSON.stringify(err));
    }
    return true;
  }

  deleteTempFile(files: Array<string>): boolean {
    for (let file of files) {
      let path = new fileUri.FileUri(file).path;
      fs.unlink(path, (err: BusinessError) => {
        if (err) {
          JsLogger.error('remove file： %{public}s failed，errMsg：%{public}s，errCode：%{public}s', path, err.message,
            err.code);
          return false;
        } else {
          JsLogger.info('remove file： %{public}s succeed', path);
        }
      });
    }
    return true;
  }
}
